---
title: ""
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
    - \usepackage{caption}
    - \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}


```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, arrow, readr, tidyr, glue, argparse, here, purrr, stringr, dplyr, knitr, kableExtra);

# Working directory and command line argument setup
current_script = "generate_tables_and_figures/gen_baseline_outputs/src/gen_baseline_outputs.Rmd"
here::i_am(current_script)
source(here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "PAIRWISE_BALANCE_FILE",
  "JOINT_BALANCE_FILE",
  "OUTCOME_LABELS_FILE",
  "CONFIG_FILE",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()
  
```


```{r}

source('R/baseline_output_functions.R')

pairwise_stats <- read_csv(cl_args$PAIRWISE_BALANCE_FILE, show_col_types = F)
joint_stats <- read_csv(cl_args$JOINT_BALANCE_FILE, show_col_types = F)

ylabels <- read_csv(cl_args$OUTCOME_LABELS_FILE, show_col_types = F) %>%
  rename(outcome = value)

params <- read_yaml(cl_args$CONFIG_FILE)

source('../R/table_functions.R')
table_config <- read_yaml('../hand/tables_config.yaml')

```

```{r}

baseline_vars <- tibble(
  outcome = c(params$baseline_demos_varlist, 
              params$baseline_outcomes_varlist, 
              params$baseline_uphat_varlist,
              params$baseline_arrests_varlist, 
              params$baseline_vics_varlist,
              params$baseline_incar_varlist)) %>%
  mutate(order = row_number())

baseline_stats <- pairwise_stats %>%
  filter(window == 'pre') %>% 
  mutate(outcome = gsub("_pre", "", outcome)) %>% 
  filter(outcome %in% baseline_vars$outcome) %>% 
  left_join(ylabels, by = "outcome") 

```

\blandscape

```{r}

table <- printFullSampleTable(baseline_stats, joint_stats, "full_sample")

table

timestamp <- get_timestamp()
writeLines(table, glue(cl_args$OUT_DIR, "/baselines_primary_up_to_date.tex"))
writeLines(table, glue(cl_args$OUT_DIR, "/baselines_primary_{timestamp}.tex"))

```

\newpage

```{r}

table <- printSubgroupTable(baseline_stats, joint_stats, "pathway", params$subgroup_order_and_label_map)

table

writeLines(table, glue(cl_args$OUT_DIR, "/baselines_pathway_up_to_date.tex"))
writeLines(table, glue(cl_args$OUT_DIR, "/baselines_pathway_{timestamp}.tex"))
```


\elandscape
